#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 crane <crane@his-pc>
#
# Distributed under terms of the MIT license.


"""


    1
   / \
  2   3
 / \
4   5


类似于链表: 1,2,4 逆转为4,2,1. 写法和逆转链表完全一致.

    4
   / \
  5   2
     / \
    3   1


"""


class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None

class Solution:
    def upsideDownBinaryTree(self, root):
        # NOTE: 写法和逆转链表完全一致
        pre_root, pre_right, cur = None, None, root

        while cur:
            # save
            save_root, save_left, save_right = cur, cur.left, cur.right

            # update: pivot
            cur.left = pre_right
            cur.right = pre_root

            # drive loop
            cur = save_left
            pre_root = save_root
            pre_right = save_right

        return pre_root


def main():
    print("start main")

    n2 = TreeNode(2)
    n3 =TreeNode(3)
    n1 = TreeNode(1)
    n1.left, n1.right = n2, n3
    s = Solution()
    ret = s.upsideDownBinaryTree(n1)
    print(ret.val)
    print(ret.left.val)
    print(ret.right.val)

if __name__ == "__main__":
    main()
